package yxy.game.pm2.command.infinite;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.module.RedisLock;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.BattleMessage;
import yxy.game.pm2.message.InfiniteMessage;
import yxy.game.pm2.module.infinite.InfiniteHandle;
import yxy.game.pm2.module.infinite.InfiniteModule;

import java.util.Collection;

/** 神将试炼 神将试炼战斗开始 */
@MessageType(proto = Command.InfiniteChanllengeExecute, classtype = InfiniteMessage.InfiniteChanllengeExecuteRequest.class)
public class CMD_InfiniteChanllengeExecute extends Command<InfiniteMessage.InfiniteChanllengeExecuteRequest> {

	@Override
	public void execute(MessageSource messageSource, InfiniteMessage.InfiniteChanllengeExecuteRequest request) {
		String playerCode = messageSource.getTag();
		BattleMessage.BattleExecuteRequest battleReq = request.getBattleReq();

		InfiniteMessage.InfiniteChanllengeExecuteResponse.Builder response = InfiniteMessage.InfiniteChanllengeExecuteResponse.newBuilder();

		RedisLock lock = InfiniteModule.lock(playerCode);
		try {
			if (lock.tryLock()) {
				InfiniteModule infiniteModule = InfiniteModule.get(playerCode);
				if (infiniteModule == null) {
					send(messageSource, response, Result.ModuleNotOpen);// 模块没开启
					return;
				}
				InfiniteHandle handle = new InfiniteHandle();
				Collection<InfiniteMessage.InfiniteBattle> resps = handle.battleResponseExecute(playerCode, battleReq);
				if (resps == null) {
					send(messageSource, response, Result.ParamError);
					return;
				}
				infiniteModule = InfiniteModule.get(playerCode);

				response.addAllBattleResp(resps);
				response.setBest(infiniteModule.getBest());
				response.addAllBox(infiniteModule.rewardBox());
				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			lock.unlock();
		}
	}

	private void send(MessageSource messageSource, InfiniteMessage.InfiniteChanllengeExecuteResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}